<template>
  <div class="banner-manage">
    <div class="header">
      <h2>轮播图管理</h2>
      <el-button type="primary" @click="handleAdd">添加轮播图</el-button>
    </div>

    <el-table :data="banners" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column label="图片" width="180">
        <template #default="scope">
          <el-image 
            style="width: 100px; height: 60px"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="link" label="链接" />
      <el-table-column prop="sort" label="排序" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="banner-uploader"
            :action="''"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="banner-image" />
            <el-icon v-else class="banner-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const banners = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const imageUrl = ref('')
const imageFile = ref(null)

const form = ref({
  id: null,
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'number' }]
}

const formRef = ref()

// 获取轮播图列表
const getBanners = async () => {
  loading.value = true
  try {
    const response = await request.get('/banner/list')
    if (response.code === 0) {
      banners.value = response.data
    } else {
      ElMessage.error(response.msg || '获取轮播图列表失败')
    }
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 处理图片变更
const handleImageChange = (file) => {
  imageFile.value = file.raw
  imageUrl.value = URL.createObjectURL(file.raw)
}

// 添加轮播图
const handleAdd = () => {
  dialogTitle.value = '添加轮播图'
  form.value = {
    id: null,
    title: '',
    imageUrl: '',
    link: '',
    sort: 0,
    status: 1
  }
  imageUrl.value = ''
  imageFile.value = null
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  dialogTitle.value = '编辑轮播图'
  form.value = { ...row }
  imageUrl.value = row.imageUrl
  imageFile.value = null
  dialogVisible.value = true
}

// 删除轮播图
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
      type: 'warning'
    })
    const response = await request.delete(`/banner/delete/${row.id}`)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      getBanners()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除轮播图失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const formData = new FormData()
    formData.append('title', form.value.title)
    if (form.value.link) {
      formData.append('link', form.value.link)
    }
    formData.append('sort', form.value.sort)
    formData.append('status', form.value.status)
    
    if (form.value.id) {
      formData.append('id', form.value.id)
    }
    
    if (imageFile.value) {
      formData.append('imageFile', imageFile.value)
    }
    
    const url = form.value.id ? '/banner/update' : '/banner/add'
    console.log('Request URL:', url)
    console.log('Form Data:', Object.fromEntries(formData.entries()))
    
    const response = await request({
      method: form.value.id ? 'put' : 'post',
      url: url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.code === 0) {
      ElMessage.success(form.value.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      getBanners()
    } else {
      ElMessage.error(response.msg || (form.value.id ? '更新失败' : '添加失败'))
      console.error('提交失败:', response)
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    ElMessage.error(form.value.id ? '更新失败' : '添加失败')
  }
}

onMounted(() => {
  getBanners()
})
</script>

<style scoped>
.banner-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.banner-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.banner-uploader:hover {
  border-color: #409eff;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.banner-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style> 